package com.cnvp.paladin.controller;

import java.io.File;
import java.net.URL;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;

import com.cnvp.paladin.core.BaseController;
import com.cnvp.paladin.core.MyCallback;
import com.cnvp.paladin.model.Equipment;
import com.cnvp.paladin.model.Room;
import com.cnvp.paladin.model.Scene;
import com.cnvp.paladin.model.Sceneconfig;
import com.cnvp.paladin.model.SysUser;
import com.cnvp.paladin.model.SysUserRole;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.upload.UploadFile;

public class SceneconfigController extends BaseController {
	boolean flag = false;

	/**
	 * if the user is superadmin
	 * 
	 * @return return the userID
	 */
	public int issuperadmin() {
		SysUser currentUser = (SysUser) SecurityUtils.getSubject().getPrincipal();
		int userID = currentUser.get("id");
		List<SysUserRole> sur = currentUser.getRoles();
		for (SysUserRole sr : sur) {
			if (sr.getInt("role_id") == 4)
				flag = true;
		}
		return userID;
	}

	public void index() {
		setAttr("page", Sceneconfig.dao.paginate(getParaToInt(0, 1), 10));
	}

	public void find() {
		Map<String, Object> json = new HashMap<String, Object>();
		if (isPost()) {
			int userID = issuperadmin();
			int id = getParaToInt("sceneconfig.id") == null ? -1 : getParaToInt("sceneconfig.id");
			int scene_id = getParaToInt("sceneconfig.scene_id") == null ? -1 : getParaToInt("sceneconfig.scene_id");
			int equipment_id = getParaToInt("sceneconfig.equipment_id") == null ? -1
					: getParaToInt("sceneconfig.equipment_id");
			String tag = getPara("sceneconfig.tag");
			String room_name = getPara("sceneconfig.room_name");
			String type = getPara("sceneconfig.type");
			String equipment_logicid = getPara("sceneconfig.equipment_logic_id");
			String status = getPara("sceneconfig.status");
			String param1 = getPara("sceneconfig.param1");
			String param2 = getPara("sceneconfig.param2");
			String param3 = getPara("sceneconfig.param3");
			String param4 = getPara("sceneconfig.param4");
			String param5 = getPara("sceneconfig.param5");
			String findSql = "(1=1) and ";
			if (flag == true) {
				if (id != -1)
					findSql += "id=" + id + " and ";
				if (scene_id != -1)
					findSql += "scene_id =" + scene_id + " and ";
				if (equipment_id != -1)
					findSql += "equipment_id=" + equipment_id + " and ";
				if (tag != null && !tag.isEmpty())
					findSql += "tag =" + "\"" + tag + "\"" + " and ";
				if (room_name != null && !room_name.isEmpty())
					findSql += "room_name =" + "\"" + room_name + "\"" + " and ";
				if (type != null && !type.isEmpty())
					findSql += "type =" + "\"" + type + "\"" + " and ";
				if (equipment_logicid != null && !equipment_logicid.isEmpty())
					findSql += "equipment_logic_id =" + equipment_logicid + " and ";
				if (status != null && !status.isEmpty())
					findSql += "status like '%" + status + "%'" + " and ";
				if (param1 != null && !param1.isEmpty())
					findSql += "param1 like '%" + param1 + "%'" + " and ";
				if (param2 != null && !param2.isEmpty())
					findSql += "param2 like '%" + param2 + "%'" + " and ";
				if (param3 != null && !param3.isEmpty())
					findSql += "param3 like '%" + param3 + "%'" + " and ";
				if (param4 != null && !param4.isEmpty())
					findSql += "param4 like '%" + param4 + "%'" + " and ";
				if (param5 != null && !param5.isEmpty())
					findSql += "param5 like '%" + param5 + "%'" + " and ";
			} else {
				if (id != -1)
					findSql += "id=" + id + " and ";
				findSql += "user_id=" + userID + " and ";
				if (scene_id != -1)
					findSql += "scene_id =" + scene_id + " and ";
				if (equipment_id != -1)
					findSql += "equipment_id=" + equipment_id + " and ";
				if (tag != null && !tag.isEmpty())
					findSql += "tag =" + "\"" + tag + "\"" + " and ";
				if (room_name != null && !room_name.isEmpty())
					findSql += "room_name =" + "\"" + room_name + "\"" + " and ";
				if (type != null && !type.isEmpty())
					findSql += "type =" + "\"" + type + "\"" + " and ";
				if (equipment_logicid != null && !equipment_logicid.isEmpty())
					findSql += "equipment_logic_id =" + equipment_logicid + " and ";
				if (status != null && !status.isEmpty())
					findSql += "status like '%" + status + "%'" + " and ";
				if (param1 != null && !param1.isEmpty())
					findSql += "param1 like '%" + param1 + "%'" + " and ";
				if (param2 != null && !param2.isEmpty())
					findSql += "param2 like '%" + param2 + "%'" + " and ";
				if (param3 != null && !param3.isEmpty())
					findSql += "param3 like '%" + param3 + "%'" + " and ";
				if (param4 != null && !param4.isEmpty())
					findSql += "param4 like '%" + param4 + "%'" + " and ";
				if (param5 != null && !param5.isEmpty())
					findSql += "param5 like '%" + param5 + "%'" + " and ";
			}
			findSql += " (1=1);";

			List<Sceneconfig> data = Sceneconfig.dao.where(findSql);
			// 正确情况
			if (data.size() != 0) {
				json.put("code", "0");
				json.put("data", data);
				json.put("msg", "success");
			} else {
				// 无返回数据的情况
				json.put("code", "305");
				json.put("data", data);
				json.put("msg", "返回数据为空");
			}

		}
		renderJson(json);

	}

	public void getlist() {
		Map<String, Object> json = new HashMap<String, Object>();
		int userID = issuperadmin();
		if (flag == true) {
			List<Sceneconfig> data = Sceneconfig.dao.where("");
			json.put("code", "0");
			json.put("data", data);
			json.put("msg", "success");
		} else {
			String findSql = "(1=1) and ";
			findSql += "user_id=" + userID + " and ";
			findSql += " (1=1);";
			List<Sceneconfig> data = Sceneconfig.dao.where(findSql);
			json.put("code", "0");
			json.put("data", data);
			json.put("msg", "success");
		}

		renderJson(json);
	}

	public void create() {
		if (isPost()) {
			String is_app = getPara("is_app");
			int userID = issuperadmin();
			int id = getParaToInt("sceneconfig.id") == null ? -1 : getParaToInt("sceneconfig.id");
			int scene_id = getParaToInt("sceneconfig.scene_id") == null ? -1 : getParaToInt("sceneconfig.scene_id");
			int equipment_id = getParaToInt("sceneconfig.equipment_id") == null ? -1
					: getParaToInt("sceneconfig.equipment_id");
			String tag = getPara("sceneconfig.tag");
			String room_name = getPara("sceneconfig.room_name");
			String type = getPara("sceneconfig.type");
			String equipment_logic_id = getPara("sceneconfig.equipment_logic_id");
			String status = getPara("sceneconfig.status");
			String param1 = getPara("sceneconfig.param1");
			String param2 = getPara("sceneconfig.param2");
			String param3 = getPara("sceneconfig.param3");
			String param4 = getPara("sceneconfig.param4");
			String param5 = getPara("sceneconfig.param5");
			String scene_name = getPara("sceneconfig.scene_name");
			String image = getPara("sceneconfig.image");
			String findEquipmentId = "equipment_logic_id =" + "\"" + equipment_logic_id + "\"" + " " + "and" + " "
					+ "room_name =" + "\"" + room_name + "\"" + " and  user_id = " + "\"" + userID + "\""
					+ " and tag = " + "\"" + tag + "\";";
			List<Sceneconfig> equipmentData = Sceneconfig.dao.where(findEquipmentId);
			if ((null == equipmentData || equipmentData.size() == 0)) {
				renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"设备逻辑id或场不存在或者错误\"}");
			} else {
				// 这里许多的equipmentid等等需要修改
				String findEquipmentLogicId = "logic_id =" + "\"" + equipment_logic_id + "\"" + " and user_id = " + "\""
						+ userID + "\";";
				List<Equipment> equipmentData1 = Equipment.dao.where(findEquipmentLogicId);
				Equipment a = equipmentData1.get(0);
				Format format = new SimpleDateFormat("hhmmssSSS");
				// Format format = new SimpleDateFormat("yyMMddhh");
				String Id = format.format(new Date());
				int id1 = Integer.valueOf(Id).intValue();
				Sceneconfig sc = getModel(Sceneconfig.class, "sceneconfig").set("id", id1).set("scene_id", -1)
						.set("equipment_id", a.get("id")).set("user_id", userID).set("tag", tag).set("type", type);
				sc.save();
				if ("1".equals(is_app)) {
					renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"success\"}");
				} else {
					redirect(getControllerKey());
				}
				return;
				// }
			}
		} else {
			Sceneconfig data = new Sceneconfig();
			setAttr("data", data);
			render("form.html");
		}
	}

	public void update() {
		String is_app = getPara("is_app");
		if (isPost()) {
			int userID = issuperadmin();
			String flag = getPara("sceneconfig.id");
			String tag = getPara("sceneconfig.tag");
			String equipment_logic_id = getPara("sceneconfig.equipment_logic_id");
			String scene_name = getPara("sceneconfig.scene_name");
			String new_scene_name = getPara("sceneconfig.new_scene_name");
			String param1 = getPara("sceneconfig.param1");
			String param2 = getPara("sceneconfig.param2");
			String param3 = getPara("sceneconfig.param3");
			int id = 0;
			// 检查設備是否是否存在
			String findSql = "equipment_logic_id =" + "\"" + equipment_logic_id + "\"" + " " + "and" + " "
					+ "scene_name =" + "\"" + scene_name + "\"" + " and  user_id = " + "\"" + userID + "\""
					+ " and tag = " + "\"" + tag + "\";";
			String selectSql = "select * from cnvp_sceneconfig where " + findSql;
			List<Sceneconfig> scf = Sceneconfig.dao.where(findSql);
			if (scf.size() == 0 || scf.isEmpty()) {
				renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
			} else {
				String findSql1 = "logic_id =" + "\"" + equipment_logic_id + "\";";
				List<Equipment> scf1 = Equipment.dao.where(findSql1);
				Equipment a = scf1.get(0);
				// 检验是否非空字段全部填写
				// Sceneconfig sc = getModel(Sceneconfig.class,
				// "sceneconfig").set("id", equipment_logic_id + a.get("id"))
				// .set("scene_id", -1).set("equipment_id", a.get("id"));
				if (null == scene_name || null == equipment_logic_id) {
					renderJson("{\"code\":\"301\",\"data\":\"\",\"msg\":\"缺少参数\"}");
				} else {
					if ("1".equals(is_app)) {
						List<Record> user = Db.find(selectSql);
						Record user1 = user.get(0).set("scene_name", new_scene_name).set("param1", param1)
								.set("param2", param2).set("param3", param3);
						Db.update("cnvp_sceneconfig", user1);
						renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"success\"}");
					} else {
						List<Record> user = Db.find(selectSql);
						Record user1 = user.get(0).set("scene_name", new_scene_name).set("param1", param1)
								.set("param2", param2).set("param3", param3);
						Db.update("cnvp_sceneconfig", user1);
						redirect(getControllerKey());
					}
					return;
				}
			}
		} else {
			// renderJson("{\"code\":\"301\",\"data\":\"\",\"msg\":\"缺少参数\"}");
			setAttr("data", Sceneconfig.dao.findById(getParaToInt()));
			render("form.html");
		}
	}

	public void delete() {
		String is_app = getPara("is_app");
		int userID = issuperadmin();
		String scene_name = getPara("sceneconfig.scene_name");
		String equipment_logic_id = getPara("sceneconfig.equipment_logic_id");
		String tag = getPara("sceneconfig.tag");
		if ((null == scene_name || scene_name.length() == 0)
				|| (null == equipment_logic_id || equipment_logic_id.length() == 0)) {
			renderJson("{\"code\":\"301\",\"data\":\"\",\"msg\":\"缺少参数\"}");
		} else {
			String findSql = "equipment_logic_id =" + "\"" + equipment_logic_id + "\"" + " " + "and" + " "
					+ "scene_name =" + "\"" + scene_name + "\"" + " and  user_id = " + "\"" + userID + "\";";
			List<Sceneconfig> scf = Sceneconfig.dao.where(findSql);
			if (scf.size() == 0 || scf.isEmpty()) {
				renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"设备逻辑id或场景名称:不存在或者错误\"}");
			} else {
				String DeleteSql = "DELETE FROM cnvp_sceneconfig WHERE equipment_logic_id =" + "\"" + equipment_logic_id
						+ "\"" + " " + "AND scene_name =" + "\"" + scene_name + "\"" + " AND user_id = " + "\"" + userID
						+ "\"" + " and tag = " + "\"" + tag + "\";";
				MyCallback callbcack1 = new MyCallback(DeleteSql);
				Db.execute(callbcack1);
				if ("1".equals(is_app)) {
					renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"success\"}");
				} else {
					redirect(getControllerKey());
				}
			}
		}
	}

	public void deleteAll() {
		String is_app = getPara("is_app");
		Integer[] ids = null;
		if (!getPara("sceneconfig.id").isEmpty()) {
			ids = getParaValuesToInt("sceneconfig.id");
		} else {
			renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
			return;
		}

		boolean flag = true;
		for (Integer id : ids) {
			Sceneconfig sc = Sceneconfig.dao.findById(id);
			if (sc != null) {
				sc.delete();
			} else {
				flag = false;
			}
		}
		if ("1".equals(is_app) && flag == true) {
			renderJson("{\"code\":\"0\",\"data\":\"\",\"msg\":\"sucess\"}");
		} else if ("1".equals(is_app) && flag == false) {
			renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"该主键不存在\"}");
		} else {
			redirect(getControllerKey());
		}
	}

	public void portrait() {

		if ("POST".equals(getRequest().getMethod())) {
			// 获取上传的文件
			UploadFile pf1 = getFile("sceneconfig.file");
			String image_name = getPara("sceneconfig.image_name");
			String scene_name = getPara("sceneconfig.scene_name");
			String equipment_logic_id = getPara("sceneconfig.equipment_logic_id");
			String tag = getPara("sceneconfig.tag");
			if (null == pf1) {
				renderJson("{\"code\":\"307\",\"data\":\"\",\"msg\":\"没有接收到图片\"}");
			} else {
				if (tag.equals("0")) {
					String filename2 = pf1.getFileName();
					System.out.println(filename2);
					// 获取当前时间
					Format format = new SimpleDateFormat("yyyyMMddhhmmssSSS");
					String filenamebe = format.format(new Date());
					// 取文件后缀名
					if (null != image_name && null != scene_name && null != equipment_logic_id && null != tag) {
						// 是否要给上jpg需要继续讨论
						String filename = image_name + ".jpg";
						// 获取服务器的路径
						URL url = SceneController.class.getResource("/");
						String getPath = url.getPath().substring(0, url.getPath().length() - 16);
						// 设置头像的路径
						String path = getPath + "Static/images/protrait/";
						String portrait = path + filename;
						File file = pf1.getFile();
						file.renameTo(new File(portrait));
						this.setAttr("fileName", portrait);
						// 更新数据库用户信息

						int userID = issuperadmin();
						String findSceneconfigId = "equipment_logic_id =" + "\"" + equipment_logic_id + "\"" + " "
								+ "and" + " " + "scene_name =" + "\"" + scene_name + "\"" + " and  user_id = " + "\""
								+ userID + "\"" + " and tag = " + "\"" + tag + "\";";
						List<Sceneconfig> sceneconfigData = Sceneconfig.dao.where(findSceneconfigId);
						Sceneconfig sceneconfig = sceneconfigData.get(0);
						String file_name = path + sceneconfig.get("image") + ".jpg";
						File deleteFile = new File(file_name);
						// SysUser currentUser = (SysUser)
						// SecurityUtils.getSubject().getPrincipal();
						// currentUser =
						// SysUser.dao.findById(currentUser.get("id"));
						// File deleteFile1 = new File(path +
						// currentUser.get("url"));
						if (deleteFile.exists())
							deleteFile.delete();
						// if (deleteFile1.exists())
						// deleteFile1.delete();
						System.out.println("================fileName:" + filename);
						// 以json格式进行渲染
						Record record = new Record().set("id", sceneconfig.get("id")).set("image", image_name);
						Db.update("cnvp_sceneconfig", record);
						String is_app = getPara("is_app");
						if ("1".equals(is_app)) {
							renderJson("{\"code\":\"0\",\"msg\":\"success\"}");
						} else {
							alertAndGoback("修改头像成功！");
						}
					} else {
						renderJson("{\"code\":\"301\",\"msg\":\"缺少参数\"}");
					}
				} else if (tag.equals("1")) {
					if (null != image_name && null != scene_name) {
						// 是否要给上jpg需要继续讨论
						String filename = image_name + ".jpg";
						// 获取服务器的路径
						URL url = SceneController.class.getResource("/");
						String getPath = url.getPath().substring(0, url.getPath().length() - 16);
						// 设置头像的路径
						String path = getPath + "Static/images/protrait/";
						String portrait = path + filename;
						File file = pf1.getFile();
						file.renameTo(new File(portrait));
						this.setAttr("fileName", portrait);
						// 更新数据库用户信息

						int userID = issuperadmin();
						String findSceneconfigId = "scene_name =" + "\"" + scene_name + "\"" + " and  user_id = " + "\""
								+ userID + "\"" + " and tag = " + "\"" + tag + "\";";
						List<Sceneconfig> sceneconfigData = Sceneconfig.dao.where(findSceneconfigId);
						// Sceneconfig sceneconfig = sceneconfigData.get(0);
						// String file_name = path + sceneconfig.get("image") +
						// ".jpg";
						// File deleteFile = new File(file_name);
						for (int i = 0; i < sceneconfigData.size(); i++) {
							Sceneconfig sceneconfig = sceneconfigData.get(i);
							String file_name = path + sceneconfig.get("image") + ".jpg";
							File deleteFile = new File(file_name);
							if (deleteFile.exists())
								deleteFile.delete();
							// if (deleteFile1.exists())
							// deleteFile1.delete();
							System.out.println("================fileName:" + filename);
							// 以json格式进行渲染
							Record record = new Record().set("id", sceneconfig.get("id")).set("image", image_name);
							Db.update("cnvp_sceneconfig", record);
						}
						// SysUser currentUser = (SysUser)
						// SecurityUtils.getSubject().getPrincipal();
						// currentUser =
						// SysUser.dao.findById(currentUser.get("id"));
						// File deleteFile1 = new File(path +
						// currentUser.get("url"));

						String is_app = getPara("is_app");
						if ("1".equals(is_app)) {
							renderJson("{\"code\":\"0\",\"msg\":\"success\"}");
						} else {
							alertAndGoback("修改头像成功！");
						}
					} else {
						renderJson("{\"code\":\"301\",\"msg\":\"缺少参数\"}");
					}

				}
			}
			// Equipment data = new Equipment();
			// setAttr("data", data);
			// render("portrait.html");
		}

	}

	public void portrait_download() {
		Map<String, Object> json = new HashMap<String, Object>();
		String scene_name = getPara("sceneconfig.scene_name");
		String equipment_logic_id = getPara("sceneconfig.equipment_logic_id");
		String tag = getPara("sceneconfig.tag");
		int userID = issuperadmin();
		String findSql = "(1=1) and ";
		if (userID != -1)
			findSql += "user_id=" + userID + " and ";
		if (scene_name != null && !scene_name.isEmpty())
			findSql += "scene_name =" + "\"" + scene_name + "\"" + " and ";
		if (equipment_logic_id != null && !equipment_logic_id.isEmpty())
			findSql += "equipment_logic_id =" + equipment_logic_id + " and ";
		if (tag != null && !tag.isEmpty())
			findSql += "tag =" + "\"" + tag + "\"" + " and ";
		findSql += " (1=1);";
		List<Sceneconfig> data = Sceneconfig.dao.where(findSql);
		Sceneconfig sceneconfig = data.get(0);
		URL url = SceneController.class.getResource("/");
		String getPath = url.getPath().substring(0, url.getPath().length() - 16);
		// 设置头像的路径
		String path = getPath + "Static/images/protrait/";
		// String filename = path;
		// String filename = path + sceneconfig.get("image");
		// String filename = sceneconfig.get("image");
		if (data.size() != 0) {
			json.put("code", "0");
			json.put("data", sceneconfig.get("image"));
			json.put("msg", "success");
		} else {
			// 无返回数据的情况
			json.put("code", "305");
			json.put("data", "");
			json.put("msg", "返回数据为空");
		}
		renderJson(json);
	}

}